package service

import (
	"fmt"
	"sync"

	"gitee.com/flwwsg/apiserver/model"
	"gitee.com/flwwsg/apiserver/pkg/constvar"
	"gitee.com/flwwsg/apiserver/pkg/util"
)

func ListUser(username string, offset, limit int) ([]*model.UserInfo, uint64, error) {
	users, count, err := model.ListUser(username, offset, limit)
	if err != nil {
		return nil, count, err
	}
	ids := make([]uint64, len(users))
	for i, user := range users {
		ids[i] = user.Id
	}
	wg := sync.WaitGroup{}
	userList := model.UserList{
		Lock:  new(sync.Mutex),
		IdMap: make(map[uint64]*model.UserInfo, len(users)),
	}

	errChan := make(chan error, 1)
	finished := make(chan bool, 1)
	//并发获取用户信息
	for _, u := range users {
		wg.Add(1)
		go func(u *model.UserModel) {
			defer wg.Done()
			shortID, err := util.GenShortId()
			if err != nil {
				errChan <- err
				return
			}
			userList.Lock.Lock()
			defer userList.Lock.Unlock()
			userList.IdMap[u.Id] = &model.UserInfo{
				Id:       u.Id,
				Username: u.Username,
				SayHello: fmt.Sprintf("hello %s", shortID),
				Password: u.Password,
				CreateAt: u.CreateAt.Format(constvar.TimeFormat),
				UpdateAt: u.UpdateAt.Format(constvar.TimeFormat),
			}
		}(u)
	}
	go func() {
		wg.Wait()
		close(finished)
	}()
	select {
	case <-finished:
	case err := <-errChan:
		return nil, count, err
	}
	infos := make([]*model.UserInfo, len(userList.IdMap))
	for i, id := range ids {
		infos[i] = userList.IdMap[id]
	}
	return infos, count, nil
}
